<?php


namespace app\bock\type;


use app\bock\type\bock\IBock;

class Panel
{
    /**
     * 面板区域
     * @var array
     */
    protected $area;

    protected $with;

    protected $height;

    /**
     * @param mixed $height
     */
    public function setHeight($height)
    {
        $this->height = $height;
    }

    /**
     * @param array $area
     */
    public function setArea($area)
    {
        $this->area = $area;
    }

    /**
     * @param mixed $with
     */
    public function setWith($with)
    {
        $this->with = $with;
    }

    /**
     * @return array
     */
    public function getArea()
    {
        return $this->area;
    }

    public function __construct($with, $height)
    {
        $this->setHeight($height);
        $this->setWith($with);
        $this->init();
    }

    /**
     * @return mixed
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * @return mixed
     */
    public function getWith()
    {
        return $this->with;
    }

    /**
     * 初始化区域
     */
    protected function init()
    {
        for ($i=0; $i<$this->height; $i++)
        {
            for ($j=0; $j<$this->with; $j++)
            {
                $point = new Point($i, $j);
                $this->setPointNode($point,new NodeBackGround($point));
            }
        }
    }

    public function setPointNode(Point $point, INode $node)
    {
        $this->area[$point->getRow()][$point->getCol()] = $node;
    }

    /**
     * @param Point $point
     * @return INode
     */
    public function getPointNode(Point $point)
    {
        return $this->area[$point->getRow()][$point->getCol()];
    }

    /**
     * 在某个位置绘制图形
     * @param Point $point
     * @param IBock $bock
     */
    public function draw(Point $point, $bock)
    {
        /**
         * 在某个地方绘制, 其实就是把某个地方改成需要绘制的对象
         *
         * 假设: 我想在 (0,0) (0,1) 绘制, 其实就是将这两个点改成需要绘制的对象
         */
        $bock->setStartPoint($point);
        $bock->render($this);
    }

    /**
     * 对该区域进行渲染
     */
    private function render()
    {
        $renderRes = '';

        for ($i=0; $i<$this->height; $i++)
        {
            for ($j=0; $j<$this->with; $j++)
            {
                $node = $this->getPointNode(new Point($i, $j));
                $renderRes .= $node->render();
            }

            $renderRes .= PHP_EOL;
        }

        echo $renderRes;
    }

    public function clear()
    {
        $str = '';
        for ($i=0; $i<$this->height; $i++)
        {
            $str .= PHP_EOL;
        }

        echo $str;
    }

    /**
     * 刷新当前面板
     */
    public function flush()
    {
        $this->clear();
        $this->render();
    }

}